package com.lfd.filedownload.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.filedownload.controller
 * @文件名: FileController
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/24 16:19
 * @描述：
 */
@RestController
public class FileController {
    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) throws IOException {
        // 创建文件对象
        File fileOpen = new File("D:\\lfd\\一些有用的\\一些用的\\更新aar.txt");
        // 检查文件是否存在
        if (!fileOpen.exists()) {
           throw new FileNotFoundException();
        }
        response.reset();
        //设置文件下载方式
        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileOpen.getName(), "utf-8"));
        response.setHeader("Access-Control-Allow-Origin", "*");
        //获取servlet响应输出字节流
        IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(fileOpen));
    }
}
